package multiThreadSafe2;

/**
 * # @File  : TicketSale.java
 * # @Author: Lomo
 * # @Site  : lomo.space
 * # @Date  : 2021-09-12
 * # @Desc  : 方式2 使用同步方法 保障多线程安全
 */
public class TicketSale {
    public static void main(String[] args) {
        RunnableImpl runnable = new RunnableImpl();
        // Thread t0 = new Thread(runnable);
        // Thread t1 = new Thread(runnable);
        // Thread t2 = new Thread(runnable);
        // // 开启任务
        // t0.start();
        // t1.start();
        // t2.start();
        for (int i = 0; i < 5; i ++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }

    }
}

class RunnableImpl implements Runnable {
    private int ticket = 100;

    @Override
    public void run() {
        while (true) {
            ticketSale();
        }
    }

    private synchronized void ticketSale() {
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "正在售卖第" + ticket + "张票");
            ticket --;
        }
    }
}